/**
 * author: zhou
 * date: 2017.10.19
 * description: redis 连接核心文件
 * 
 */

// 引入ioredis
const   Redis = require('ioredis'),
        { redisOptions } = require('config-lite')(__dirname),
        redisPromise = require('./redisPromise');

// 引入省市区数据
const provinceData = require('../../utils/provinceData');

// 初始化redis连接
const redis = new Redis(redisOptions);

redis.connect(async () => {
    console.log('students-server connect redis successfully');
    // 缓存省市区信息
    if (provinceData) {
        const getPipeline = redis.pipeline().get('location:data');
        const getResult = await redisPromise({}, getPipeline);
        // 如果redis中没有省市区信息,则缓存
        if (getResult.length > 0 && !getResult[0][1]) {
            const pipeline = redis.pipeline().set('location:data', JSON.stringify(provinceData));
            const result = await redisPromise({}, pipeline);
            if (result.length > 0 && result[0][1] === 'OK') {
                console.log('students-server write province data successfully');
            } else {
                console.log('students-server write province data failed...');
            }
        }
    }
});

module.exports = redis;